# !/usr/bin/env python
# -*-coding:utf-8 -*-
"""
# File       : process_schema.py
# Time       ：2023/3/12 10:26
# Author     ：Y-aong
# version    ：python 3.7
# Description：
    流程序列化类
    process serialization class
"""
from marshmallow import fields
from marshmallow_sqlalchemy import auto_field, SQLAlchemyAutoSchema

from apis.orderlines.models import Task
from apis.orderlines.models.process import Process, ProcessInstance
from apis.orderlines.schema.task_schema import TaskInstanceSchema
from public.utils.schema_utils import CustomNested, columns_to_json
from public.utils.datetime_utils import calculate_time_difference


class ProcessInstanceSchema(SQLAlchemyAutoSchema):
    process_id = auto_field()
    task_instance = CustomNested(TaskInstanceSchema, many=True, dump_only=True)
    start_time = fields.DateTime(format="%Y-%m-%d %H:%M:%S")
    end_time = fields.DateTime(format="%Y-%m-%d %H:%M:%S")

    class Meta:
        model = ProcessInstance


class ProcessInstanceExportScheme(SQLAlchemyAutoSchema):
    process_id = fields.String()
    process_instance_id = fields.String()
    namespace = fields.String()
    process_name = fields.String()
    process_status = fields.String()
    mode = fields.Function(serialize=lambda obj: '调试模式' if obj.mode == 'debug' else '运行模式')
    run_type = fields.Function(serialize=lambda obj: '手动触发' if obj.run_type == 'trigger' else '定时触发')
    process_error_info = fields.Function(serialize=lambda obj: columns_to_json(obj, 'process_error_info'))
    process_params = fields.Function(serialize=lambda obj: columns_to_json(obj, 'process_params'))
    start_time = fields.DateTime(format="%Y-%m-%d %H:%M:%S")
    end_time = fields.DateTime(format="%Y-%m-%d %H:%M:%S")
    elapsed = fields.Function(serialize=lambda obj: calculate_time_difference(obj.end_time, obj.start_time))


class ProcessSchema(SQLAlchemyAutoSchema):
    insert_time = fields.DateTime(format="%Y-%m-%d %H:%M:%S")
    update_time = fields.DateTime(format="%Y-%m-%d %H:%M:%S")

    class Meta:
        model = Process


class TaskRunningSchema(SQLAlchemyAutoSchema):
    insert_time = fields.DateTime(format="%Y-%m-%d %H:%M:%S")
    update_time = fields.DateTime(format="%Y-%m-%d %H:%M:%S")
    process_id = auto_field()

    class Meta:
        model = Task


class ProcessRunningSchema(SQLAlchemyAutoSchema):
    class Meta:
        model = Process
        exclude = ['id', 'update_time', 'insert_time']
